package com.aaa.service.impl;

import com.aaa.dao.RoleDao;
import com.aaa.dao.impl.RoleDaoImpl;
import com.aaa.entity.Role;
import com.aaa.entity.TreeMenu;
import com.aaa.service.ResourceService;
import com.aaa.service.RoleService;

import java.util.*;

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao = new RoleDaoImpl();
    private ResourceService resourceService = new ResourceServiceImpl();

    @Override
    public List<Map<String, Object>> getAllRole() {
        return roleDao.getAllRole();
    }

    @Override
    public Map<String, Object> findRole(Integer pageNumber, Integer pageSize, String roleName) {
        int count = findRoleCount(roleName);
        pageNumber = (pageNumber - 1) * pageSize;
        List<Map<String, Object>> list = roleDao.findRole(pageNumber, pageSize, roleName);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("list", list);


        return map;
    }

    @Override
    public int findRoleCount(String roleName) {
        return roleDao.findRoleCount(roleName);
    }

    @Override
    public int updateRoleById(Role role) {

        return roleDao.updateRoleById(role);
    }

    @Override
    public int addRole(Role role) {

        return roleDao.addRole(role);
    }

    @Override
    public int deleteStaffByRoleId(int roleId) {

        return roleDao.deleteStaffByRoleId(roleId);
    }

    @Override
    public List<TreeMenu> getMenuList(int roleId) {
        return roleDao.getMenuList(roleId);
    }

    @Override
    public int updateMenuList(Integer roleId, String resourceIds) {

        try {
            Set<Integer> outids = roleDao.getRsourceByRoleId(roleId);
            Set<Integer> temp =  new HashSet<>();

            Set<Integer> intids = new HashSet<>();

            String str  = resourceIds.substring(1,resourceIds.length()-1);
            System.out.println(str);
            String [] strs = str.split(",");
            for (int i = 0; i < strs.length ; i++) {
                intids.add(Integer.parseInt(strs[i]));
            }
            temp.addAll(intids);

            if (intids.removeAll(outids)){
                for (Integer id:intids) {
                    resourceService.addResourceAndRole(roleId,id);
                }
            }

            if (outids.removeAll(temp)){
                for (Integer id:outids) {
                    resourceService.deleteResourceByResourceId(id);
                }

            }







            return 1;
        }catch (Exception e){
            return 0;
        }

    }

}
